<template>
	<view class="login">
		<view class="uni-common-mt">
			<view class='uni-form-item uni-column'>
				<view class="login_label">登录</view>
			</view>
			<view class='uni-form-item uni-column'>
				<view>
					<input class="uni-input" v-model="username" focus placeholder="账号" />
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view>
					<input class="uni-input" v-model="password" type="password" placeholder="密码" />
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view>
					<button type="primary" @click="user_login">登录</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		EventSourcePolyfill
	} from 'event-source-polyfill';
	export default {
		data() {
			return {
				username: '', // 用户名
				password: '', // 密码
				token: null, // 登录成功后获取的 Token
				sseConnection: null // SSE 连接
			};
		},
		methods: {
			async user_login() {
				try {
					const res = await uni.request({
						url: "http://localhost:8082/user/login",
						method: 'post',
						data: {
							'username': this.username,
							'password': this.password
						},
						header: {
							'Content-Type': 'application/json'
						}
					});

					if (res.statusCode === 200 && res.data.code === 1) {

						// 登录成功
						this.token = res.data.data; // 假设后端返回的 token 在 token 字段

						uni.setStorageSync('token', this.token);
						uni.showToast({
							title: "登录成功",
							icon: 'success'
						});

						// 建立 SSE 连接
						this.establishSSEConnection();

						// 调用获取用户信息的接口
						const userInfoRes = await uni.request({
							url: "http://localhost:8082/user/profile",
							method: 'get',
							header: {
								'Authorization': 'Bearer ' + this.token
							}
						});

						if (userInfoRes.statusCode === 200 && userInfoRes.data.code === 1) {
							const role = userInfoRes.data.data.roleType;
							uni.setStorageSync('userRole', role);
							let url = '';

							// 跳转到对应页面
							uni.navigateTo({
								url: role === 'EMPLOYEE' ?
									'/pages/customtabbar/customtabbar' : '/pages/customtabbar/customtabbar'
							});
						} else {
							uni.showToast({
								title: "获取用户信息失败",
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: "用户名或密码错误，请重试",
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: "请求接口失败" + err.message,
						icon: 'none',
					});
				}
			},
			establishSSEConnection() {
				const username = this.username;
				const token = this.token;
				const url = `http://localhost:8082/sse/alerts/${username}`; // 不需要拼 token 到 URL

				// 关闭旧连接
				if (this.sseConnection) {
					this.sseConnection.close();
				}

				// 使用 polyfill 建立连接并传入 headers
				this.sseConnection = new EventSourcePolyfill(url, {
					headers: {
						'Authorization': `Bearer ${token}`
					},
					heartbeatTimeout: 60000 // 心跳超时时间（可选）
				});

				this.sseConnection.onopen = () => {
					console.log('✅ SSE连接已建立（polyfill）');
				};

				this.sseConnection.onmessage = (event) => {
					console.log('📩 默认事件数据:', event.data);
				};

				this.sseConnection.addEventListener('alert', (event) => {
					console.log('🚨 收到预警:', event.data);
					this.alertMessage = event.data;
					uni.showToast({
						title: this.alertMessage,
						icon: 'none'
					});
				});

				this.sseConnection.onerror = (error) => {
					console.error('❌ SSE连接错误:', error);
					// 可选：自动重连逻辑
				};
			}

		},
		mounted() {
			// 如果用户已经登录，自动建立 SSE 连接
			const token = uni.getStorageSync('token');

			// if (token) {
			// 	this.token = token;
			// 	this.establishSSEConnection();
			// }
		},
		beforeDestroy() {
			// 在组件销毁前关闭 SSE 连接
			if (this.sseConnection) {
				this.sseConnection.close();
			}
		}
	};
</script>

<style scoped>
	.login {
		padding: 20rpx 40rpx;
		margin: 200rpx 20rpx;
		text-align: center;
		background-color: #eee;

		.login_label {
			color: #333;
			margin: 0 auto;
		}

		.uni-input {
			background-color: #fff;
			height: 80rpx;
			text-align: left;
			padding-left: 10rpx;
			border-radius: 10rpx;
			font-size: 30rpx;
		}

		.uni-form-item {
			margin: 30rpx 0;
		}

		.button {
			font-size: 30rpx;
		}
	}
</style>